package com.ant.storage.service.impl;


import com.ant.storage.common.PageRecv;
import com.ant.storage.common.ResultCode;
import com.ant.storage.common.ResultPage;
import com.ant.storage.common.ResultVo;
import com.ant.storage.dto.CommodityDto;
import com.ant.storage.dto.InventoryCheckDto;
import com.ant.storage.handler.AntException;
import com.ant.storage.mapper.CommodityMapper;
import com.ant.storage.pojo.Commodity;
import com.ant.storage.pojo.Inventory;
import com.ant.storage.pojo.UserInfo;
import com.ant.storage.service.ICityService;
import com.ant.storage.service.ICommodityService;
import com.ant.storage.service.IInventoryService;
import com.ant.storage.utils.NullInspectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.BindingResult;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author melon
 * @since 2022-04-13
 */
@Service
public class CommodityServiceImpl extends ServiceImpl<CommodityMapper, Commodity> implements ICommodityService {

    @Autowired(required = false)
    CommodityMapper commodityMapper;

    @Autowired
    ICityService cityService;

    @Autowired
    public ServletContext servletContext;

    @Autowired
    public IInventoryService inventoryService;


    @Override
    public PageInfo<Commodity> getCommodityPage(CommodityDto dto) {
        try {
            PageHelper.startPage(dto.getPageIndex(), dto.getPageSize());
            QueryWrapper<Commodity> wrapper = new QueryWrapper<>();
            if (StringUtils.isNotEmpty(dto.getCommodityName())) {
                wrapper.lambda().like(Commodity::getCommodityName, dto.getCommodityName());
            }
            if (StringUtils.isNotEmpty(dto.getCommodityBarCode())) {
                wrapper.lambda().like(Commodity::getCommodityBarCode, dto.getCommodityBarCode());
            }
            if (dto.getCityId() != null) {
                wrapper.lambda().eq(Commodity::getCityId, dto.getCityId());
            }
            if (dto.getCommodityType() != null) {
                wrapper.lambda().eq(Commodity::getCommodityType, dto.getCommodityType());
            }
            wrapper.eq("is_delete", 1);
            wrapper.orderByDesc("commodity_id");
            PageInfo<Commodity> info = new PageInfo<>(this.baseMapper.selectList(wrapper));
            return info;
        } catch (Exception e) {
            throw new AntException(ResultCode.BODY_NOT_MATCH);
        }
    }

    @Override
    public PageInfo<Commodity> listPage(CommodityDto dto) {
        UserInfo userInfo = (UserInfo) servletContext.getAttribute("userInfo");
        if(userInfo==null){
            throw new AntException(ResultCode.FAILURE.getCode(),"登录超时");
        }
        try {
            PageHelper.startPage(dto.getPageIndex(), dto.getPageSize());
            QueryWrapper<Commodity> wrapper = new QueryWrapper<>();
            if (StringUtils.isNotEmpty(dto.getCommodityName())) {
                wrapper.lambda().like(Commodity::getCommodityName, dto.getCommodityName());
            }
            if (StringUtils.isNotEmpty(dto.getCommodityTypes())) {
                wrapper.lambda().in(Commodity::getCommodityType, Arrays.asList(dto.getCommodityTypes().split(",")));
            }
            wrapper.eq("is_delete", 1);
            wrapper.orderByDesc("commodity_id");
            PageInfo<Commodity> info = new PageInfo<>(this.baseMapper.selectList(wrapper));
            info.getList().stream().forEach(item -> {
                Inventory one = inventoryService.getOne(new QueryWrapper<Inventory>().eq(
                        "commodity_id", item.getCommodityId()).eq("warehouse_id",userInfo.getCityId()));
               try {
                   if(one!=null){
                       item.setGoodsAmount(one.getGoodsAmount());
                       item.setCommodityPrice(one.getGoodsPrice());
                       item.setInventoryId(one.getId());
                   }else{
                       item.setGoodsAmount(new BigDecimal("0"));
                       item.setCommodityPrice(new BigDecimal("0"));
                   }
               }catch (Exception e) {
                   throw new AntException(ResultCode.BODY_NOT_MATCH.getCode(), "数据重复"+item.getCommodityId());
               }

            });
            return info;
        } catch (Exception e) {
            throw new AntException(ResultCode.BODY_NOT_MATCH.getCode(),"查询失败");
        }
    }

    @Override
    public ResultVo saveCommodity(CommodityDto commodityDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            throw new AntException(bindingResult.getFieldError().getDefaultMessage());
        } else {
            Commodity commodity = new Commodity();
            BeanUtils.copyProperties(commodityDto, commodity);
            commodity.setCreationTime(new Date());
            if (commodityDto.getCommodityId() == null || commodityDto.getCommodityId() == 0) {
                this.baseMapper.insert(commodity);
                return ResultVo.success("添加成功");
            } else {
                this.baseMapper.updateById(commodity);
                return ResultVo.success("修改成功");
            }
        }
    }

    @Override
    public Object queryCommodity(Integer commodity_id, Integer warehouse_id) {
        return commodityMapper.queryCommodity(commodity_id, warehouse_id);
    }

    @Override
    public ResultPage queryCommodityList(PageRecv<InventoryCheckDto> pageRecv) {
        Map map = new HashMap<>();
        if (!(pageRecv.getData() == null)) {
            map = NullInspectUtil.ClassChangeMapNotNull(pageRecv.getData());
        }
        Integer page = (pageRecv.getCurrentPage() - 1) * pageRecv.getPageSize();
        Integer limit = pageRecv.getCurrentPage() * pageRecv.getPageSize();
        List<Inventory> list = commodityMapper.queryCommodityList(page, limit, map);
        //城市查询并添加
//        for (Inventory inventory : list) {
//            inventory.getCity().setName(cityService.idQuery(inventory.getWarehouseList().getCityId()));
//            inventory.getDept().setName(cityService.idQuery(inventory.getWarehouseList().getDeptId()));
//        }
        Integer count = commodityMapper.countCommodityList(map);
        return ResultPage.success("OK", list, count);
    }

    @Override
    public ResultVo uploadCommodity(MultipartFile file) {
        Commodity commodity;//定义员工POJO类
        UserInfo userInfo = (UserInfo) servletContext.getAttribute("userInfo");
        //解析出来的封装好要返回的对象
        List<Commodity> commodityList = new ArrayList<>();
        //插入数据库时，需要日期格式转换
        SimpleDateFormat format = new SimpleDateFormat("yyyy-mm-dd");
        if (file.isEmpty()) {
            // 先判断客户端上传的excel有没有效
            throw new RuntimeException("文件错误");
        }
        try {
            //获得上传的excel文件
            //HSSFWorkbook workbook = new HSSFWorkbook(new POIFSFileSystem(file.getInputStream()));
            XSSFWorkbook workbook = new XSSFWorkbook(file.getInputStream());
            //获取第一个sheet
            XSSFSheet sheet = workbook.getSheetAt(0);
            //获取行数
            int rowNums = sheet.getPhysicalNumberOfRows();
            //遍历行数
            for (int i = 1; i < rowNums; i++) {
                commodity = new Commodity();
                //得到该行的数据
                XSSFRow row = sheet.getRow(i);
                if (row != null) {
                    //获得该行的单元格数量，并遍历出单元格
                    int cellNums = row.getPhysicalNumberOfCells();
                    for (int j = 0; j < cellNums; j++) {
                        XSSFCell cell = row.getCell(j);
                        cell.setCellType(CellType.STRING);
                        if (cell != null) {
                            //开始填装Emp实体属性
                            String value = cell.getStringCellValue();
                            if (value == null) {
                                value = "";//如果值是空的则空字符串
                            }
                            commodity.setCityId(1);
                            // commodity.setCommodityBarCode(commodityMapper.selectLastID());
                            //每一个字段对应的index
                            switch (j) {
                                case 0:
                                    commodity.setCommodityBarCode(value);
                                    break;
                                case 1:
                                    commodity.setCommodityName(value);
                                    break;
                                case 2:
                                    commodity.setCommodityUnits(value);
                                    break;
                                case 3:
                                    commodity.setCommodityType(Integer.valueOf(value));
                                    break;
                            }
                            commodity.setCreationBy(userInfo.getNameId().toString());
                            commodity.setRemark("系统导入");
                            commodity.setCommodityPrice(new BigDecimal("0"));
                            commodity.setCreationTime(new Date());
                        }
                    }
                    //一个完整emp
                    // 将添加好的emp添加到list
                    Commodity selectOne = this.baseMapper.selectOne(new QueryWrapper<Commodity>()
                            .eq("commodity_bar_code", commodity.getCommodityBarCode()));
                    if (selectOne == null) {
                        this.baseMapper.insert(commodity);
                    }
                    //  commodityList.add(commodity);
                }
            }
            return ResultVo.success("上传成功");

        } catch (Exception e) {
            e.printStackTrace();
            throw new AntException(ResultCode.BODY_NOT_MATCH);
        }
    }
}
